/**
 @Name：文件上传
 @Author：wanghui
 */

layui.define(function (exports) {
    var admin = layui.admin,
        $ = layui.jquery;

    var callback_obj;
    obj = {
        //设置回调函数
        set_callback_obj: function (set_obj) {
            callback_obj = set_obj;
            //示例回调函数
            /*var callback_obj = {
                up_image: function (res_url) {
                    if (res_url) {
                        //这里是处理回调后的url
                    }
                    return true;//如果需要判断数量就在这里操作返回false
                }
            }*/
        },
        //设置上传参数
        upload: function (model = 'images', quality = '100', max_file_size = 2) {
            var aliyun_token;
            admin.req({
                url: layui.setter.apiHost + '/helper/aliyun_token',
                data: {model: model},
                success: function (result) {
                    if (result.code == 0) {
                        aliyun_token = result.data;
                        //自动组装按钮id
                        var plupload_button_ids = new Array();
                        $(".plupload_btn").each(function () {
                            plupload_button_ids.push($(this).attr('id'))
                        })
                        //监控上传按钮的点击事件
                        var plupload_btn_id = '';
                        $(".plupload_btn").on('click', function () {
                            plupload_btn_id = $(this).attr('id');
                        })

                        var plupload_multipart_params = '';
                        var plupload_load_index = '';
                        var uploader = new plupload.Uploader({
                                browse_button: plupload_button_ids,
                                url: aliyun_token.host,
                                chunk_size: '0',
                                unique_names: true,
                                flash_swf_url: '../lib/plupload/Moxie.swf',
                                silverlight_xap_url: '../lib/plupload/Moxie.xap',
                                filters: {
                                    max_file_size: max_file_size + 'mb',
                                    mime_types: [
                                        {title: "Image files", extensions: "jpg,gif,png,jpeg"},
                                    ],
                                    prevent_duplicates: true //不允许选取重复文件
                                },
                                resize: {quality: quality, preserve_headers: false},
                                init: {
                                    //选择文件后执行
                                    FilesAdded: function (up, files) {
                                        var next = true;
                                        if ($('#' + plupload_btn_id).hasClass('is_callback')) {
                                            next = false;
                                            try {
                                                //调用自定义函数处理回调,比如控制上传的数量(plupload_btn_id 上传图片的按钮id)
                                                fun_name = plupload_btn_id;
                                                //如果存在自定义函数名称就调用自定义，否则默认查找id命名的函数
                                                if ($('#' + plupload_btn_id).attr('callback_fun')) {
                                                    fun_name = $('#' + plupload_btn_id).attr('callback_fun');
                                                }
                                                if (callback_obj[fun_name].call(this, {id_name: plupload_btn_id, file_num: files.length})) {
                                                    next = true;
                                                }
                                            } catch (e) {
                                            }
                                        }
                                        //弹出正在上传的提示
                                        if (next) {
                                            plupload_load_index = layer.msg('正在上传，请稍后', {
                                                icon: 16, shade: 0.01, time: 1000000000
                                            });
                                            uploader.start();
                                        } else {
                                            //清空上传队列
                                            $.each(files, function (index, item) {
                                                uploader.removeFile(item);
                                            })
                                        }
                                    },
                                    BeforeUpload: function (up, file) {
                                        plupload_multipart_params = {
                                            'key': aliyun_token.dir + file.target_name,
                                            'policy': aliyun_token.policy,
                                            'OSSAccessKeyId': aliyun_token.accessid,
                                            'success_action_status': '200', //让服务端返回200,不然，默认会返回204
                                            'signature': aliyun_token.signature,
                                        };
                                        up.setOption({
                                            'multipart_params': plupload_multipart_params
                                        });
                                    },
                                    //单个文件上传完成
                                    FileUploaded: function (up, file, result) {
                                        var res_url = aliyun_token.domain + aliyun_token.dir + file.target_name;
                                        if (plupload_btn_id) {
                                            //当图片按钮上存在is_callback class属性的时候说明需要回调自定义的函数
                                            if ($('#' + plupload_btn_id).hasClass('is_callback')) {
                                                try {
                                                    //调用自定义函数处理回调(plupload_btn_id 上传图片的按钮id,res_url图片地址)
                                                    fun_name = plupload_btn_id;
                                                    //如果存在自定义函数名称就调用自定义，否则默认查找id命名的函数
                                                    if ($('#' + plupload_btn_id).attr('callback_fun')) {
                                                        fun_name = $('#' + plupload_btn_id).attr('callback_fun');
                                                    }
                                                    callback_obj[fun_name].call(this, {id_name: plupload_btn_id, url: res_url})
                                                } catch (e) {
                                                }
                                            } else {
                                                $("#" + plupload_btn_id).parent().find('img').attr('src', res_url).removeClass('layui-hide');
                                                $("#" + plupload_btn_id).parent().find('a').attr('href', res_url);
                                                $("#" + plupload_btn_id).parent().find('[type="hidden"]').val(res_url);
                                            }
                                        }
                                    },
                                    //全部文件上传完成
                                    UploadComplete: function (up, files) {
                                        layer.close(plupload_load_index);
                                    },
                                    //上传进度
                                    UploadProgress: function (up, files) {

                                    },
                                    //返回错误
                                    Error: function (up, err) {
                                        if (err.message) {
                                            layer.msg(err.message);
                                        } else {
                                            layer.msg('上传失败');
                                        }
                                    }
                                }
                            })
                        ;
                        uploader.init();
                    }
                }
            });
        }
    }

    exports('plupload', obj);
})